<?php

namespace plugins\yifang_backend_account\utils\encrypt;

class Rsa_produce
{
    /**
     * 获取秘钥对
     * @return array
     */
    public static function getData(){
        $opensslConfigPath = config("custom.winOpensslConfigPath","");
        $config = array(
            "digest_alg" => "sha512",
            "private_key_bits" =>2048, // 512  1024 2048 4096
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
        );
        //创建密钥对
        $res = openssl_pkey_new($config);
        if(!$res && $opensslConfigPath) {
            $config['config'] = $opensslConfigPath;
            $res = openssl_pkey_new($config);
        }
        //生成私钥
        openssl_pkey_export($res, $privkey,null,$config);
        //生成公钥
        $pubKey = openssl_pkey_get_details($res);
        $pubKey = $pubKey["key"];
        openssl_free_key($res);

        $return=array();
        $return["privatekey"]=$privkey;
        $return["publicKey"]=$pubKey;
        return $return;
    }

    /**
     * 获取秘钥和证书
     * @return array
     */
    public static function getRsaData()
    {
        $dn = array(
            "countryName" => "CN",
            "stateOrProvinceName" => "Liaoning",
            "localityName" => "Dalian",
            "organizationName" => "Dalian NetDragon Technology",
            "organizationalUnitName" => "Yifang E-commerce",
            "commonName" => "Yifang E-commerce",
            "emailAddress" => "1724827556@qq.com"
        );
        $privkeypass = 'asd12546';
        $numberofdays = 365 * 5;
        $opensslConfigPath = config("custom.winOpensslConfigPath","");
        $config = array(
            "digest_alg" => "sha512",
            "private_key_bits" =>2048, // 512  1024 2048 4096
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
        );
        $res = openssl_pkey_new($config);
        if(!$res && $opensslConfigPath) {
            $config['config'] = $opensslConfigPath;
            $res = openssl_pkey_new($config);
        }

        // 生成证书
        $csr = openssl_csr_new($dn, $res,$config);
        $sscert = openssl_csr_sign($csr, null, $res, $numberofdays,$config);
        //导出证书$csrkey
        openssl_x509_export($sscert, $csrkey);
        //导出密钥$privatekey
        openssl_pkcs12_export($sscert, $privatekey, $res, $privkeypass);
        //获取私钥
        openssl_pkcs12_read($privatekey, $certs, $privkeypass);
        $prikeyid = $certs['pkey'];
        $csrStr = $certs['cert'];
        //x获取公钥
        $pub_key = openssl_pkey_get_public($csrkey);
        $keyData = openssl_pkey_get_details($pub_key);
        $public = $keyData['key'];

        openssl_free_key($res);
        $return=array();
        $return["privatekey"]=$prikeyid;
        $return["publicKey"]=$public;
        $return["csrStr"]=$csrStr;
        return $return;
    }

}


